package com.sanqi.work.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sanqi.common.utils.DateUtils;
import com.sanqi.common.utils.SQMapUtil;
import com.sanqi.common.utils.SqSimpleExcelUtil;
import com.sanqi.work.domain.UserAccountExcelBean;
import com.sanqi.work.domain.WorkUser;
import com.sanqi.work.manager.IWorkUserAccountManager;
import com.sanqi.work.manager.impl.WorkUserManager;
import com.sanqi.work.mapper.WorkUserMapper;
import com.sanqi.work.service.IWorkUserService;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 员工Service业务层处理
 * 
 * @author duany
 * @date 2025-09-24
 */
@Service
public class WorkUserServiceImpl extends ServiceImpl<WorkUserMapper, WorkUser> implements IWorkUserService 
{
    @Autowired
    private WorkUserMapper workUserMapper;
    @Autowired
    private WorkUserManager workUserManager;
    @Autowired
    private IWorkUserAccountManager workUserAccountManager;

    /**
     * 查询员工
     * 
     * @param id 员工主键
     * @return 员工
     */
    @Override
    public WorkUser selectWorkUserById(String id)
    {
        return workUserMapper.selectWorkUserById(id);
    }

    /**
     * 查询员工列表
     * 
     * @param workUser 员工
     * @return 员工
     */
    @Override
    public List<WorkUser> selectWorkUserList(WorkUser workUser)
    {
        return workUserMapper.selectWorkUserList(workUser);
    }

    /**
     * 新增员工
     * 
     * @param workUser 员工
     * @return 结果
     */
    @Override
    public int insertWorkUser(WorkUser workUser)
    {
        workUser.setCreateTime(DateUtils.getNowDate());
        boolean save = save(workUser);
        return save ? 1 : 0;
    }

    /**
     * 修改员工
     * 
     * @param workUser 员工
     * @return 结果
     */
    @Override
    public int updateWorkUser(WorkUser workUser)
    {
        workUser.setUpdateTime(DateUtils.getNowDate());
        return workUserMapper.updateById(workUser);
    }

    /**
     * 批量删除员工
     * 
     * @param ids 需要删除的员工主键
     * @return 结果
     */
    @Override
    public int deleteWorkUserByIds(String[] ids)
    {
        return workUserMapper.deleteWorkUserByIds(ids);
    }

    /**
     * 删除员工信息
     * 
     * @param id 员工主键
     * @return 结果
     */
    @Override
    public int deleteWorkUserById(String id)
    {
        return workUserMapper.deleteWorkUserById(id);
    }

    @Override
    public void impUserExcel(String workplaceId, Workbook workBook) {
        List<WorkUser> userList = this.getUserByWorkplace(workplaceId);
        Map<String, WorkUser> userMap = SQMapUtil.ListToMap(userList, WorkUser::getIdNo);
        Set<String> idNoList = userList.stream().map(WorkUser::getIdNo).collect(Collectors.toSet());
        //比对在职员工并进行添加
        //在职员工
        List<WorkUser> activeUserList = SqSimpleExcelUtil.excelBeanList(workBook, "在职档案", WorkUser.class);
        activeUserList.forEach(user -> {
            String userSex = user.getUserSex();
            if(StrUtil.isNotBlank(userSex)) {
                if(StrUtil.equals("男", StrUtil.trim(userSex))) {
                    userSex = "1";
                }
                if(StrUtil.equals("女", StrUtil.trim(userSex))) {
                    userSex = "2";
                }
                user.setUserSex(userSex);
            }
            String phoneNumber = user.getPhoneNumber();
            if(StrUtil.isNotBlank(phoneNumber)) {
                try {
                    BigDecimal decimal = new BigDecimal(phoneNumber);
                    user.setPhoneNumber(String.valueOf(decimal.longValue()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        //离职员工
        List<WorkUser> exUserList = SqSimpleExcelUtil.excelBeanList(workBook, "离职档案", WorkUser.class);
        exUserList.forEach(user -> {
            String userSex = user.getUserSex();
            if(StrUtil.isNotBlank(userSex)) {
                if(StrUtil.equals("男", StrUtil.trim(userSex))) {
                    userSex = "1";
                }
                if(StrUtil.equals("女", StrUtil.trim(userSex))) {
                    userSex = "2";
                }
                user.setUserSex(userSex);
            }
            String phoneNumber = user.getPhoneNumber();
            if(StrUtil.isNotBlank(phoneNumber)) {
                try {
                    BigDecimal decimal = new BigDecimal(phoneNumber);
                    user.setPhoneNumber(String.valueOf(decimal.longValue()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                
            }
        });
        //新增在职
        List<WorkUser> newActiveList = ListUtil.list(false);
        for (WorkUser workUser : activeUserList) {
            String idNo = workUser.getIdNo();
            if(!idNoList.contains(idNo)) {
                newActiveList.add(workUser);
            }
        }
        //新增离职
        List<WorkUser> newExList = ListUtil.list(false);
        for (WorkUser workUser : exUserList) {
            String idNo = workUser.getIdNo();
            if(!idNoList.contains(idNo)) {
                newExList.add(workUser);
            } else {
                String userStatus = workUser.getUserStatus();
                if("2".equals(userStatus)) {
                    continue;
                } else {
                    String no = workUser.getIdNo();
                    if(StrUtil.isBlank(no)) {
                        continue;
                    }
                    WorkUser user = userMap.get(no);
                    user.setEffectiveDate(workUser.getEffectiveDate());
                    user.setUserStatus("2");
                    this.updateById(user);
                }
            }
        }
        if(CollUtil.isNotEmpty(newActiveList)) {
            for (WorkUser workUser : newActiveList) {
                workUser.setId(IdUtil.getSnowflakeNextIdStr());
                workUser.setWorkplace(workplaceId);
                workUser.setUserStatus("1");
                this.save(workUser);
            }
        }
        if(CollUtil.isNotEmpty(newExList)) {
            for (WorkUser workUser : newExList) {
                workUser.setId(IdUtil.getSnowflakeNextIdStr());
                workUser.setWorkplace(workplaceId);
                workUser.setUserStatus("2");
                this.save(workUser);
            }
        }
    }

    @Override
    public List<WorkUser> getUserByWorkplace(String workplaceId) {
        return workUserManager.getUserByWorkplace(workplaceId);
    }

    @Override
    public boolean editUserAccount(Workbook workBook) {
        try {
            Sheet sheet = workBook.getSheetAt(0);
            List<UserAccountExcelBean> list = SqSimpleExcelUtil.excelBeanList(sheet, UserAccountExcelBean.class);
            for (UserAccountExcelBean userAccountExcelBean : list) {
                String userIdNo = userAccountExcelBean.getUserIdNo();
                List<WorkUser> userList = this.getUserByIdNo(userIdNo);
                if (CollUtil.isNotEmpty(userList)) {
                    WorkUser workUser = userList.get(0);
                    String userId = workUser.getId();
                    workUserAccountManager.editUserAccount(userId, userAccountExcelBean.getUserAccount(),
                            userAccountExcelBean.getOPCode());
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
        
        return true;
    }
    
    @Override
    public List<WorkUser> getUserByIdNo(String idNo){
        List<WorkUser> list = this.lambdaQuery().eq(WorkUser::getIdNo, idNo)
                .orderByDesc(WorkUser::getUpdateTime, WorkUser::getCreateTime).list();
        return list;
    }
}
